package myservice.android.activities;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.ListRow;
import myservice.android.utilities.SearchRunnable;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SearchResultsActivity extends BaseActivity {
	
	private ImageView callsIcon;
	private TextView callsLabel;
	private LinearLayout callsResults;
	
	private ImageView interestedIcon;
	private TextView interestedLabel;
	private LinearLayout interestedResults;	
	
	private ImageView territoriesIcon;
	private TextView territoriesLabel;
	private LinearLayout territoriesResults;	
	
	private ImageView publicationsIcon;
	private TextView publicationsLabel;
	private LinearLayout publicationsResults;	
	
	private Button closeButton;
	private Button searchAgainButton;
	
	private boolean searchExecuted = false;
	
	private String searchQuery;	
	private boolean searchCalls;
	private boolean searchInterested;
	private boolean searchTerritories;
	private boolean searchPublications;	

	@Override
	protected void initializeLayoutIdAndTitle() {
		layoutId = R.layout.search_results;
		activityTitle = Global.res.getString(R.string.title_search_results);
	}

	@Override
	protected void retrieveViews() {

		callsIcon = (ImageView) findViewById(R.id.callsIcon);
		callsLabel = (TextView) findViewById(R.id.callsLabel);		
		callsResults = (LinearLayout) findViewById(R.id.callsResults);
		
		interestedIcon = (ImageView) findViewById(R.id.personsIcon);
		interestedLabel = (TextView) findViewById(R.id.personsLabel);		
		interestedResults = (LinearLayout) findViewById(R.id.personsResults);	
		
		territoriesIcon = (ImageView) findViewById(R.id.territoriesIcon);
		territoriesLabel = (TextView) findViewById(R.id.territoriesLabel);		
		territoriesResults = (LinearLayout) findViewById(R.id.territoriesResults);	
		
		publicationsIcon = (ImageView) findViewById(R.id.publicationsIcon);
		publicationsLabel = (TextView) findViewById(R.id.publicationsLabel);		
		publicationsResults = (LinearLayout) findViewById(R.id.publicationsResults);		
		
		closeButton = (Button) findViewById(R.id.closeButton);
		searchAgainButton = (Button) findViewById(R.id.newSearchButton);		

	}

	@Override
	protected void loadActivityParameters() {
		
		searchQuery = activityParameters.getString("search_query");	
		searchCalls = activityParameters.getBoolean("calls");
		searchInterested = activityParameters.getBoolean("interested");
		searchTerritories = activityParameters.getBoolean("territories");
		searchPublications = activityParameters.getBoolean("publications");		
		
	}

	@Override
	protected void assignListeners() {	
		
		closeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
			
		});
		
		searchAgainButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View button) {				
						
				final Dialog dialog = new Dialog(SearchResultsActivity.this);
				dialog.setContentView(R.layout.search_criteria);
				dialog.setTitle(Global.res.getString(R.string.title_search));
				
				Button searchButton = (Button) dialog.findViewById(R.id.searchButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				final EditText searchString = (EditText) dialog.findViewById(R.id.searchString);
				searchString.setText(searchQuery);
				final CheckBox callsCheckbox = (CheckBox) dialog.findViewById(R.id.callsCheckbox);
				callsCheckbox.setChecked(searchCalls);				
				final CheckBox interestedCheckbox = (CheckBox) dialog.findViewById(R.id.interestedCheckbox);
				interestedCheckbox.setChecked(searchInterested);
				final CheckBox territoriesCheckbox = (CheckBox) dialog.findViewById(R.id.territoriesCheckbox);
				territoriesCheckbox.setChecked(searchTerritories);
				final CheckBox publicationsCheckbox = (CheckBox) dialog.findViewById(R.id.publicationsCheckbox);
				publicationsCheckbox.setChecked(searchPublications);				
				
				searchButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						
						if (!callsCheckbox.isChecked() && !interestedCheckbox.isChecked() && !territoriesCheckbox.isChecked() && !publicationsCheckbox.isChecked()) {
							Global.displayToast(SearchResultsActivity.this, Global.res.getString(R.string.message_search_no_checkboxes));
							return;
						}
						
						searchQuery = searchString.getText().toString();
						searchCalls = callsCheckbox.isChecked();
						searchInterested = interestedCheckbox.isChecked();
						searchPublications = publicationsCheckbox.isChecked();
						searchTerritories = territoriesCheckbox.isChecked();
						performSearch();	
						dialog.dismiss();					
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);								
				dialog.show();								
						
			}        	
        });   		
		
		OnClickListener toggleCallsResults = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!callsLabel.getText().toString().contains("(0")) { // At least one result exists
					if (callsResults.isShown()) { // Collapse					
						callsIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
						callsResults.setVisibility(View.GONE);					
					} else { // Expand					
						callsIcon.setImageDrawable(Global.res.getDrawable(R.drawable.expanded));
						callsResults.setVisibility(View.VISIBLE);				
					}
				}
			}			
		};
		callsLabel.setOnClickListener(toggleCallsResults);
		callsIcon.setOnClickListener(toggleCallsResults);
		
		OnClickListener toggleInterestedResults = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!interestedLabel.getText().toString().contains("(0")) { // At least one result exists
					if (interestedResults.isShown()) { // Collapse					
						interestedIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
						interestedResults.setVisibility(View.GONE);					
					} else { // Expand					
						interestedIcon.setImageDrawable(Global.res.getDrawable(R.drawable.expanded));
						interestedResults.setVisibility(View.VISIBLE);				
					}
				}
			}			
		};
		interestedLabel.setOnClickListener(toggleInterestedResults);
		interestedIcon.setOnClickListener(toggleInterestedResults);	
		
		OnClickListener toggleTerritoriesResults = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!territoriesLabel.getText().toString().contains("(0")) { // At least one result exists
					if (territoriesResults.isShown()) { // Collapse					
						territoriesIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
						territoriesResults.setVisibility(View.GONE);					
					} else { // Expand					
						territoriesIcon.setImageDrawable(Global.res.getDrawable(R.drawable.expanded));
						territoriesResults.setVisibility(View.VISIBLE);				
					}
				}
			}			
		};
		territoriesLabel.setOnClickListener(toggleTerritoriesResults);
		territoriesIcon.setOnClickListener(toggleTerritoriesResults);	
		
		OnClickListener togglePublicationsResults = new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!publicationsLabel.getText().toString().contains("(0")) { // At least one result exists
					if (publicationsResults.isShown()) { // Collapse					
						publicationsIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
						publicationsResults.setVisibility(View.GONE);					
					} else { // Expand					
						publicationsIcon.setImageDrawable(Global.res.getDrawable(R.drawable.expanded));
						publicationsResults.setVisibility(View.VISIBLE);				
					}
				}
			}			
		};
		publicationsLabel.setOnClickListener(togglePublicationsResults);
		publicationsIcon.setOnClickListener(togglePublicationsResults);		

	}		
	
	private void performSearch() {
		
		// Remove characters from the query that may break the SQL
		searchQuery = searchQuery.replace("'", "").replace("%", "");
		
		activityTitleView.setText(Global.res.getString(R.string.title_search_results)+" ('"+searchQuery+"')");
		
		// Initially, all results are collapsed, and result count is 0
		callsIcon.setVisibility(View.VISIBLE);
		callsLabel.setVisibility(View.VISIBLE);		
		callsResults.setVisibility(View.GONE);
		callsResults.removeAllViews();
		callsIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
		callsLabel.setText(Global.res.getString(R.string.label_search_calls)+" (0)");
		
		interestedIcon.setVisibility(View.VISIBLE);
		interestedLabel.setVisibility(View.VISIBLE);			
		interestedResults.setVisibility(View.GONE);
		interestedResults.removeAllViews();
		interestedIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
		interestedLabel.setText(Global.res.getString(R.string.label_search_interested)+" (0)");	
		
		territoriesIcon.setVisibility(View.VISIBLE);
		territoriesLabel.setVisibility(View.VISIBLE);			
		territoriesResults.setVisibility(View.GONE);
		territoriesResults.removeAllViews();
		territoriesIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
		territoriesLabel.setText(Global.res.getString(R.string.label_search_territories)+" (0)");	
		
		publicationsIcon.setVisibility(View.VISIBLE);
		publicationsLabel.setVisibility(View.VISIBLE);			
		publicationsResults.setVisibility(View.GONE);
		publicationsResults.removeAllViews();
		publicationsIcon.setImageDrawable(Global.res.getDrawable(R.drawable.collapsed));
		publicationsLabel.setText(Global.res.getString(R.string.label_search_publications)+" (0)");		
		
		if (!searchCalls) {
			callsIcon.setVisibility(View.GONE);
			callsLabel.setVisibility(View.GONE);
		}
		
		if (!searchInterested) {
			interestedIcon.setVisibility(View.GONE);
			interestedLabel.setVisibility(View.GONE);
		}	
		
		if (!searchTerritories) {
			territoriesIcon.setVisibility(View.GONE);
			territoriesLabel.setVisibility(View.GONE);
		}	
		
		if (!searchPublications) {
			publicationsIcon.setVisibility(View.GONE);
			publicationsLabel.setVisibility(View.GONE);
		}			
		
		// Do the processing-intensive work asynchronously to avoid freezing UI
		AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
			
			private ProgressDialog pd;						
             
			 @Override
			 protected void onPreExecute() {				 								 
				 pd = new ProgressDialog(SearchResultsActivity.this);
				 pd.setTitle(Global.res.getString(R.string.title_searching));
				 pd.setMessage(Global.res.getString(R.string.message_please_wait));
				 pd.setCancelable(false);
				 pd.setIndeterminate(true);
				 pd.show();
			 }
			 
			 @Override
			 protected Void doInBackground(Void... arg0) {
				 
				if (searchCalls) {
				 							 				 				 
					// Search calls		
				 
				    final LinearLayout callsList = callsResults;
					
					int callCount = 0;
					
					String sql = "SELECT callid,year,month,date,calls.personid AS call_personid,biblestudy,calls.comments AS call_comments,name FROM calls "+
					             "LEFT JOIN persons ON calls.personid=persons.personid WHERE calls.timestamp<>"+Global.TIMESTAMP_DELETED;
					
					// Do not include calls to inactive persons unless the "Display inactive persons" check box is selected
					if (!Global.showInactives)
						sql = sql + " AND (calls.personid=0 OR territoryid<>0 OR (calls.personid<>0 AND status>0))";
					
					if (!searchQuery.equals(""))
						sql = sql + " AND calls.comments LIKE '%"+searchQuery+"%'";
					
					sql = sql + " ORDER BY year DESC, month DESC, date DESC";
					
					Cursor c = Database.select(sql);
					while (c.moveToNext()) {
						
			    		callCount++;
			    		final ListRow lr = new ListRow(SearchResultsActivity.this);
			    		
			    		lr.setBackgroundDrawable(Global.res.getDrawable(android.R.drawable.list_selector_background));
			    		
			    		lr.id=c.getLong(c.getColumnIndex("callid"));
			    		
			    		String date = Global.getFormattedDate(c.getInt(c.getColumnIndex("year")), c.getInt(c.getColumnIndex("month")), c.getInt(c.getColumnIndex("date")));			    		
			    		
						if (c.getInt(c.getColumnIndex("call_personid"))!=0) {
							lr.firstLine.setText(c.getString(c.getColumnIndex("name"))+" ("+date+")");
						} else {
							lr.firstLine.setText(date);
						}    		
			    		
			    		lr.secondLine.setText(c.getString(c.getColumnIndex("call_comments")));
			    		int status = c.getInt(c.getColumnIndex("biblestudy"));
			    		if (status == 0)
			    			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.call_icon));
			    		else
			    			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.bible_study));
			    		
			    		lr.setOnClickListener(new OnClickListener() {
	
							@Override
							public void onClick(View arg0) {
								
								 Intent i = new Intent(getApplicationContext(),CallActivity.class);
							     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
							     i.putExtra("call_id",lr.id);			     
							     startActivity(i);	
								
							}
			    			
			    		});
			    		
			    		// Update the UI elements (cannot be run within this thread)
						SearchResultsActivity.this.runOnUiThread(new SearchRunnable(SearchResultsActivity.this, callsList, lr, callsLabel, callCount));    		     		
						
					}
						
					c.close();
				
				}
				
				if (searchInterested) {
		 				 
					// Search interested ones		
				 
				    final LinearLayout interestedList = interestedResults;
					
					int interestedCount = 0;
					
					String sql = "SELECT * FROM persons WHERE timestamp<>"+Global.TIMESTAMP_DELETED;
					if (!Global.showInactives)
						sql = sql + " AND status<>0";
					if (!searchQuery.equals(""))
						sql = sql + " AND (name LIKE '%"+searchQuery+"%' OR comments LIKE '%"+searchQuery+"%' OR street LIKE '%"+searchQuery+
						            "%' OR houseapartment LIKE '%"+searchQuery+"%' OR townregion LIKE '%"+searchQuery+"%')";
					Cursor c = Database.select(sql);
					while (c.moveToNext()) {
						
			    		interestedCount++;
			    		final ListRow lr = new ListRow(SearchResultsActivity.this);
			    		
			    		lr.setBackgroundDrawable(Global.res.getDrawable(android.R.drawable.list_selector_background));
			    		
			    		lr.id=c.getLong(c.getColumnIndex("personid"));			    					    		
			    		
						lr.firstLine.setText(c.getString(c.getColumnIndex("name")));   		
			    		
			    		lr.secondLine.setText(c.getString(c.getColumnIndex("comments")));
			    		
			    		int status = c.getInt(c.getColumnIndex("status"));
                		if (status==0)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.person_inactive));
                		else if (status==1)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.person_interested));
                		else if (status==2)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.person_magreader));
                		else if (status==3)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.person_study));
			    		
			    		lr.setOnClickListener(new OnClickListener() {
	
							@Override
							public void onClick(View arg0) {
								
								 Intent i = new Intent(getApplicationContext(),PersonActivity.class);
							     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
							     i.putExtra("person_id",lr.id);			     
							     startActivity(i);	
								
							}
			    			
			    		});
			    		
			    		// Update the UI elements (cannot be run within this thread)
						SearchResultsActivity.this.runOnUiThread(new SearchRunnable(SearchResultsActivity.this, interestedList, lr, interestedLabel, interestedCount));    		     		
						
					}
						
					c.close();
				
				}			
				
				if (searchTerritories) {
	 				 
					// Search territories		
				 
				    final LinearLayout territoriesList = territoriesResults;
					
					int territoriesCount = 0;
					
					String sql = "SELECT * FROM territories WHERE timestamp<>"+Global.TIMESTAMP_DELETED;
					if (!searchQuery.equals(""))
						sql = sql + " AND (name LIKE '%"+searchQuery+"%' OR comments LIKE '%"+searchQuery+"%')";
					Cursor c = Database.select(sql);
					while (c.moveToNext()) {
						
			    		territoriesCount++;
			    		final ListRow lr = new ListRow(SearchResultsActivity.this);
			    		
			    		lr.setBackgroundDrawable(Global.res.getDrawable(android.R.drawable.list_selector_background));
			    		
			    		lr.id=c.getLong(c.getColumnIndex("territoryid"));			    					    		
			    		
						lr.firstLine.setText(c.getString(c.getColumnIndex("name")));   		
			    		
			    		lr.secondLine.setText(c.getString(c.getColumnIndex("comments")));
			    		
			    		int type = c.getInt(c.getColumnIndex("type"));
                		if (type==0)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.territory));
                		else if (type==1)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.street));
                		else if (type==2)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.house));
                		else if (type==3)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.apartment_house));
                		else if (type==4)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.staircase));
                		else if (type==5)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.apartment));   
			    		
			    		lr.setOnClickListener(new OnClickListener() {
	
							@Override
							public void onClick(View arg0) {
								
								 Intent i = new Intent(getApplicationContext(),TerritoryElementActivity.class);
							     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
							     i.putExtra("territory_id",lr.id);	
							     i.putExtra("mode",0);							     
							     startActivity(i);	
								
							}
			    			
			    		});
			    		
			    		// Update the UI elements (cannot be run within this thread)
						SearchResultsActivity.this.runOnUiThread(new SearchRunnable(SearchResultsActivity.this, territoriesList, lr, territoriesLabel, territoriesCount));    		     		
						
					}
						
					c.close();
				
				}			
				
				if (searchPublications) {
	 				 
					// Search publications		
				 
				    final LinearLayout publicationsList = publicationsResults;
					
					int publicationsCount = 0;
					
					String sql = "SELECT * FROM publications WHERE timestamp<>"+Global.TIMESTAMP_DELETED;
					if (!searchQuery.equals(""))
						sql = sql + " AND (title LIKE '%"+searchQuery+"%')";
					Cursor c = Database.select(sql);
					while (c.moveToNext()) {
						
			    		publicationsCount++;
			    		final ListRow lr = new ListRow(SearchResultsActivity.this);
			    		
			    		lr.setBackgroundDrawable(Global.res.getDrawable(android.R.drawable.list_selector_background));
			    		
			    		lr.id=c.getLong(c.getColumnIndex("publicationid"));			    					    		
			    		
			    		lr.firstLine.setVisibility(View.GONE);
			    		
						lr.secondLine.setText(c.getString(c.getColumnIndex("title")));			    		
			    		
			    		int type = c.getInt(c.getColumnIndex("type"));
                		if (type==0)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.magazine));
                		else if (type==1)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.book));
                		else if (type==2)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.tract));
                		else if (type==3)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.video));
                		else if (type==4)
                			lr.icon.setImageDrawable(Global.res.getDrawable(R.drawable.brochure));    
			    		
			    		lr.setOnClickListener(new OnClickListener() {
	
							@Override
							public void onClick(View arg0) {
								
								 Intent i = new Intent(getApplicationContext(),PublicationActivity.class);
							     i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
							     i.putExtra("publication_id",lr.id);								     
							     startActivity(i);	
								
							}
			    			
			    		});
			    		
			    		// Update the UI elements (cannot be run within this thread)
						SearchResultsActivity.this.runOnUiThread(new SearchRunnable(SearchResultsActivity.this, publicationsList, lr, publicationsLabel, publicationsCount));    		     		
						
					}
						
					c.close();
				
				}					
									
				return null;
				 
			 }
			 
			 @Override
			 protected void onPostExecute(Void result) {
				 pd.dismiss();				 
			 }
			 
		};
		
		task.execute((Void[])null);	
		
		searchExecuted = true;		
		
	}
	
	@Override
	protected void updateUi() {	
		
		if (!searchExecuted)
			performSearch();

	}				

}
